<template>
  <div class="login">
    <!-- <img class="logo" src="../assets/images/logo_c.png" /> -->
    <div class="logo-con">
      <img src="../assets/images/logo.jpg" />
    </div>
    <div class="login-box">
      <h1>后台管理系统</h1>
      <span class="line"></span>
      <p class="tip">{{wrongMsg}}</p>
      <el-form style="margin-top: 56px;" :model="admin" ref="admin" :rules="rules">
        <el-form-item style="width: 380px;" prop="username">
          <el-input
            placeholder="请输入账号"
            v-model="admin.username"
          >
            <i slot="prepend" class="iconfont icon-yonghu"></i>
          </el-input>
        </el-form-item>
        <el-form-item style="width: 380px;" prop="password">
          <el-input placeholder="请输入密码" v-model="admin.password" type="password">
            <img
              src="../assets/images/pass.png"
              slot="prepend"
              style="display: block; width: 16px; height: 16px; max-width: 16px!important;"
            />
          </el-input>
        </el-form-item>
        <el-form-item style="width: 380px;" class="verify" prop="verifyCode">
          <el-input
            clearable
            placeholder="请输入验证码"
            v-model="admin.verifyCode"
            @keyup.enter.native="handleLogin('admin')"
          >
            <img
              src="../assets/images/security.png"
              slot="prepend"
              style="display: block; width: 16px; height: 16px; max-width: 16px!important;"
            />
            <div class="code-con" @click="changeCode" style="letter-spacing: 3px;" slot="append">
              <span v-for="(item, i) in code" :key="i">{{item}}</span>
            </div>
          </el-input>
        </el-form-item>
        <div class="btn-wrap">
          <el-button
            type="primary"
            :loading="isLogining"
            @click="handleLogin('admin')"
          >登 录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login, loginV2 } from '../api'
import { setToken } from '../util'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'

export default {
  name: 'login',
  data () {
    const checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'))
      }
      if (value.length !== 5) {
        this.createCode()
        return callback(new Error('验证码错误'))
      }
      for (let i = 0; i < value.length; i++) {
        if (String(this.code[i]).toLowerCase() !== String(value[i]).toLowerCase()) {
          this.createCode()
          return callback(new Error('验证码错误'))
        }
      }
      callback()
    }
    return {
      wrongMsg: '',
      isLogining: false,
      code: '',
      admin: {
        username: '',
        password: '',
        verifyCode: ''
      },
      rules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        verifyCode: [
          { validator: checkCode, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.createCode()
  },
  methods: {
    createCode (length) {
      length = length || 5
      let code = ''
      const random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      for (let i = 0; i < length; i++) {
        const index = Math.floor(Math.random() * random.length)
        code += random[index]
      }
      this.code = code
    },
    handleLogin (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.dealLoginV2(this.admin.username, this.admin.password);
          return
          NProgress.start();
          login({
            username: this.admin.username,
            password: this.admin.password
          }).then (res => {
            NProgress.done();
            if (res.data.code === 1) {
              let role = res.data.data.roleId
              if (role === 4 || role === 5) {
                return this.$message.error('您无权使用该系统!')
              }
              this.$store.commit('setToken', res.data.data.token)
              setToken(res.data.data.token)
              sessionStorage.setItem('role', role)
              sessionStorage.setItem('username', this.admin.username)
              this.$message({
                type: 'success',
                message: '登录成功'
              });
              this.$router.push('/')
            } else {
              this.wrongMsg = res.data.msg
            }
          }).catch (e => {
            NProgress.done();
            this.$message.error('网络异常!')
          })
        } else {
          return false
        }
      })
    },
    async fetchLogin () {
      const res = await login({
        username: this.admin.username,
        password: this.admin.password
      })
      return res
    },
    changeCode () {
      this.createCode()
    },
    dealLoginV2 (userName, passwrod) { // 登录逻辑
      NProgress.start();
      this.isLogining = true;
      loginV2({
        userName,
        passwrod
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.username;
          this.$store.commit('setAuth', list);
          this.$store.commit('setToken', res.data.data.token);
          setToken(res.data.data.token);
          sessionStorage.setItem('role', res.data.data.userRoleId);
          sessionStorage.setItem('username', list.length ? list[0].userNickname : userName);
          sessionStorage.setItem('roleTitle', list.length ? list[0].userRoleTitle : '');
          sessionStorage.setItem('enterpriseId', list.length ? list[0].enterpriseId : '');
          sessionStorage.setItem('uuid', res.data.data.userId);
          this.$message({
            type: 'success',
            message: '登录成功'
          });
          this.$router.push('/')
        } else {
          this.wrongMsg = res.data.msg
        };
        this.isLogining = false
        NProgress.done()
      })
      .catch(e => {
        this.isLogining = false;
        NProgress.done();
        this.$message.error('服务异常!')
      })
    }
  }
}
</script>
<style lang="scss">
  @import url('../assets/icon/iconfont.css');

  .login {
    position: relative;
    width: 100%;
    height: 100%;
    background-image: url('../assets/images/home_bac.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
    h1 {
      color: #333333;
      font-weight: bold;
      font-size: 30px;
    }
    .tip {
      color: #e74c3c;
      font-size: 14px;
      line-height: 20px;
      text-align: center;
    }
    .logo {
      position: absolute;
      top: 0;
      left: 80px;
      z-index: 99;
    }
    .logo-con {
      position: absolute;
      top: 0;
      left: 80px;
      width: 100px;
      height: 100px;
      // border-bottom-left-radius: 60px;
      // border-bottom-right-radius: 60px;
      // background-color: $main-color;
      // text-align: center;
      // box-shadow: 0 6px 9px #cccccc;
      img {
        width: 100%;
        height: 100%;
        border-bottom-left-radius: 50px;
        border-bottom-right-radius: 50px;
        box-shadow: 0 8px 15px #cccccc;
        // position: relative;
        // top: -8px;
        // animation: rotate infinite 1.5s ease-in-out;
      }
      @keyframes rotate {
        from { transform: rotateZ(0deg) }
        to { transform: rotateZ(360deg) }
      }
    }
    .login-box {
      position: absolute;
      top: 50%;
      left: 50%;
      padding: 73px;
      transform: translate(-50%, -50%);
      box-shadow:0px 1px 10px rgba(0,0,0,0.16);
      border-radius: 6px;
      background-color: #ffffff;
      .line {
        display: inline-block;
        width: 45px;
        height: 4px;
        background-color: $main-color;
        border-radius: 4px;
      }
      .icon {
        display: inline-block;
        width: 40px;
        height: 38px;
        background-color: #EBEBEB;
      }
      .code-con {
        user-select: none;
        -webkit-user-select: none;
        span {
          display: inline-block;
          padding: 0 5px;
          font-size: 16px;
        }
      }
      .btn-wrap {
        margin-top: 70px;
        button {
          width: 100%;
        }
      }
    }
  }
</style>
